package com.huarui.user.action;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeoutException;

import net.rubyeye.xmemcached.XMemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;

import org.apache.commons.lang.xwork.StringUtils;
import org.ewaf.framework.action.BaseAction;
import org.ewaf.framework.cookie.CookieManager;
import org.ewaf.framework.exception.BizException;
import com.huarui.company.model.Company;
import com.huarui.company.service.CompanyService;
import com.huarui.dictionary.DictionaryEnum;
import com.huarui.dictionary.model.Dictionary;
import com.huarui.dictionary.service.DictionaryReadOnlyService;
import com.huarui.employee.model.Employee;
import com.huarui.employee.service.EmployeeService;
import com.huarui.permission.service.PermissionService;
import com.huarui.user.error.UserError;
import com.huarui.user.model.CookieConstants;
import com.huarui.user.model.LoginHistory;
import com.huarui.user.model.SessionMessage;
import com.huarui.user.model.User;
import com.huarui.user.security.UserCookieAuther;
import com.huarui.user.security.UserHolder;
import com.huarui.user.service.LoginHistoryService;
import com.huarui.user.service.SessionMessageService;
import com.huarui.user.service.UserService;
import com.opensymphony.xwork2.validator.annotations.EmailValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;

public class LoginAction extends BaseAction {

	private static final long serialVersionUID = 2924526709280705961L;

	private UserService userService;

	private SessionMessageService sessionMessageService;

	private PermissionService permissionService;

	public PermissionService getPermissionService() {
		return permissionService;
	}

	public void setPermissionService(PermissionService permissionService) {
		this.permissionService = permissionService;
	}

	// private SessionMessage sessionMessage;

	private List<LoginHistory> loginhistoryList;

	private LoginHistory loginHistory;

	private LoginHistoryService loginHistoryservice;

	private String channel;

	private CompanyService companyService;

	private Company company;

	private String tokenName;

    private XMemcachedClient  memcachedClient; 
	/**
	 * 字典只读service
	 */
	private DictionaryReadOnlyService dictionaryReadOnlyService;

	/**
	 * 来源
	 */
	private List<Dictionary> sourceList;

	public LoginHistoryService getLoginHistoryservice() {
		return loginHistoryservice;
	}

	public void setLoginHistoryservice(LoginHistoryService loginHistoryservice) {
		this.loginHistoryservice = loginHistoryservice;
	}

	public List<LoginHistory> getLoginhistoryList() {
		return loginhistoryList;
	}

	public LoginHistory getLoginHistory() {
		return loginHistory;
	}

	public void setLoginHistory(LoginHistory loginHistory) {
		this.loginHistory = loginHistory;
	}

	public void setLoginhistoryList(List<LoginHistory> loginhistoryList) {
		this.loginhistoryList = loginhistoryList;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	private EmployeeService employeeService;

	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}

	public SessionMessageService getSessionMessageService() {
		return sessionMessageService;
	}

	public void setSessionMessageService(
			SessionMessageService sessionMessageService) {
		this.sessionMessageService = sessionMessageService;
	}

	public void setCompanyService(CompanyService companyService) {
		this.companyService = companyService;
	}

	public String getTokenName() {
		return tokenName;
	}

	public void setTokenName(String tokenName) {
		this.tokenName = tokenName;
	}

	private User user;

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	private Employee employee;

	private List<Integer> roleIds;

	public Employee getEmployee() {
		return employee;
	}

	public void setEmployee(Employee employee) {
		this.employee = employee;
	}

	public void setChannel(String channel) {
		this.channel = channel;
	}

	public void setCompany(Company company) {
		this.company = company;
	}

	public Company getCompany() {
		return company;
	}
	public void setMemcachedClient(XMemcachedClient memcachedClient) {
		this.memcachedClient = memcachedClient;
	}

	/**
	 * 进入登录页面
	 */
	public String input() {

		
		sourceList = dictionaryReadOnlyService
				.getDictionaryByGroup(DictionaryEnum.GROUP_SOURCE);
		// sessionMessage不等于空,说明cookie中存在用户信息,校验数据库
		SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();
		if (sessionMessage != null) {

			User user = (User) userService.getById(sessionMessage.getUserId());

			if (user != null) {

				return "logining";
			}
			
			CookieManager cookie = new CookieManager(httpServletRequest);
			cookie.removeCookie(httpServletResponse, null,
					CookieConstants.Cookie_PATH,
					CookieConstants.COOKIE_PERM);

		}
		
		tokenName="true";
		return SUCCESS;
	}

	/**
	 * 提交登录表单
	 * 
	 * @throws IOException
	 */

	/**
	 * @Validations(requiredStrings = {
	 * @RequiredStringValidator(fieldName = "user.email", shortCircuit = true,
	 *                                    key = "user.email.required"),
	 * @RequiredStringValidator(fieldName = "user.password", shortCircuit =
	 *                                    true, key = "user.password.required")
	 *                                    }, emails = {
	 *                                    @EmailValidator(fieldName =
	 *                                    "user.email", shortCircuit = true, key
	 *                                    = "user.email.format.error") }) public
	 *                                    String submit() throws IOException {
	 * 
	 *                                    HttpServletRequest request =
	 *                                    HttpUtil.getRequest();
	 * 
	 *                                    HttpServletResponse response =
	 *                                    HttpUtil.getResponse();
	 * 
	 *                                    String verifyCode =
	 *                                    request.getParameter("verifyCode");
	 * 
	 *                                    CookieManager cookie = new
	 *                                    CookieManager(request);
	 * 
	 *                                    sessionMessage =
	 *                                    UserHolder.getCurrentSessionMessage();
	 * 
	 *                                    if (sessionMessage.isLogined()) {
	 * 
	 *                                    return SUCCESS;
	 * 
	 *                                    }
	 * 
	 *                                    try {
	 * 
	 *                                    user =
	 *                                    userService.validateUser(StringUtils
	 *                                    .trim(user.getEmail()),
	 *                                    user.getPassword());
	 * 
	 *                                    } catch (Exception e) {
	 * 
	 *                                    this.addFieldError("userError", this
	 *                                    .getText
	 *                                    (UserError.WRONG_NAME_OR_EMAIL.
	 *                                    getChError()));
	 * 
	 *                                    return INPUT;
	 * 
	 *                                    }
	 * 
	 *                                    if (!user.getStatus().equals("1")) {
	 * 
	 *                                    this.addFieldError("emailActive", this
	 *                                    .getText(UserError.SHOULD_BE_UNACTIVED
	 *                                    .getChError()));
	 * 
	 *                                    return INPUT;
	 * 
	 *                                    } try { user.setGmtLastLogin(new
	 *                                    Date());
	 * 
	 *                                    
	 *                                    user.setLoginTimes(user.getLoginTimes()
	 *                                    + 1);
	 * 
	 *                                    userService.update(user);
	 * 
	 *                                    
	 *                                    loginHistory.setGmtlogin(user.getGmtLastLogin
	 *                                    ());
	 * 
	 *                                    loginHistory.setUserId(user.getId());
	 * 
	 *                                    
	 *                                    loginHistory.setIp(request.getRemoteAddr
	 *                                    ());
	 * 
	 *                                    
	 *                                    loginHistoryservice.create(loginHistory
	 *                                    );
	 * 
	 *                                    employee =
	 *                                    employeeService.getEmployeeByUserId
	 *                                    (user.getId(), user .getCompanyId());
	 * 
	 *                                    company = (Company)
	 *                                    companyService.getById
	 *                                    (user.getCompanyId()); } catch
	 *                                    (Exception e) {
	 * 
	 *                                    this.addFieldError("userError",
	 *                                    this.getText(UserError.LOGIN_FAIL
	 *                                    .getChError()));
	 * 
	 *                                    return INPUT; }
	 * 
	 *                                    String code =
	 *                                    cookie.getValue(CookieConstants
	 *                                    .COOKIE_CODE, "code");
	 * 
	 *                                    if ("true".equals(channel)) {
	 * 
	 *                                    if
	 *                                    (!verifyCode.equalsIgnoreCase(code)) {
	 * 
	 *                                    user.setPassword(null);
	 * 
	 *                                    this.addFieldError("verifyCode", this
	 *                                    .getText(UserError.VERIFYCODE_WRONG.
	 *                                    getChError()));
	 * 
	 *                                    return INPUT; } } //
	 *                                    验证成功后删除关于验证码的cookie
	 *                                    cookie.removeCookie(response, null,
	 *                                    "", "count");
	 *                                    cookie.removeCookie(response, null,
	 *                                    CookieConstants.Cookie_PATH,
	 *                                    CookieConstants.COOKIE_CODE);
	 * 
	 *                                    if (employee == null) {
	 * 
	 *                                    SessionMessage sessionMessageUser =
	 *                                    sessionMessageService
	 *                                    .getSessionMessage(user);
	 * 
	 *                                    
	 *                                    UserCookieAuther.writeSessionMessage(sessionMessageUser
	 *                                    , cookie, response);
	 * 
	 *                                    } else {
	 * 
	 *                                    // SessionMessage sessionMessage =
	 *                                    sessionMessageService //
	 *                                    .getSessionMessage(user, employee,
	 *                                    company);
	 * 
	 *                                    
	 *                                    UserCookieAuther.writeSessionMessage(sessionMessage
	 *                                    , cookie, response);
	 * 
	 *                                    }
	 * 
	 *                                    return SUCCESS;
	 * 
	 *                                    }
	 */

	/**
	 * 提交登录表单
	 * 
	 * @throws IOException
	 * @throws MemcachedException 
	 * @throws InterruptedException 
	 * @throws TimeoutException 
	 */

	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "user.email", shortCircuit = true, key = "user.email.required"),
			@RequiredStringValidator(fieldName = "user.password", shortCircuit = true, key = "user.password.required") }, emails = { @EmailValidator(fieldName = "user.email", shortCircuit = true, key = "user.email.format.error") })
	public String newSubmit(){

		String verifyCode = httpServletRequest.getParameter("verifyCode");

		try {

			user = userService.validateUser(StringUtils.trim(user.getEmail()),
					user.getPassword());

		} catch (Exception e) {

			this.addFieldError("userError", this
					.getText(UserError.WRONG_NAME_OR_EMAIL.getChError()));

			return INPUT;

		}
		if (!user.getStatus().equals("1")) {
			  
			                                     this.addFieldError("emailActive", this
			                                     .getText(UserError.SHOULD_BE_UNACTIVED
			                                     .getChError()));
			  
			                                     return INPUT;
			 
			                                     } 

		try {
			user.setGmtLastLogin(new Date());

			user.setLoginTimes(user.getLoginTimes() + 1);

			userService.update(user);

			loginHistory.setGmtlogin(user.getGmtLastLogin());

			loginHistory.setUserId(user.getId());

			loginHistory.setIp(httpServletRequest.getRemoteAddr());

			loginHistoryservice.create(loginHistory);

		} catch (Exception e) {
			
			this.addFieldError("userError", this.getText(UserError.LOGIN_FAIL
					.getChError()));

			return INPUT;
		}

		CookieManager cookie = new CookieManager(httpServletRequest);
		
		String code = cookie.getValue(CookieConstants.COOKIE_CODE, "code");
			
		String checkCode="";
		try {
			checkCode = memcachedClient.get(code);
			
			memcachedClient.delete(code);
		} catch (TimeoutException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MemcachedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		employee = employeeService.getEmployeeByUserId(user.getId(), user
				.getCompanyId(),0);

		if ("true".equals(channel)) {

			if (!verifyCode.equalsIgnoreCase(checkCode)) {

				user.setPassword(null);

				this.addFieldError("verifyCode", this
						.getText(UserError.VERIFYCODE_WRONG.getChError()));

				return INPUT;
			}
		}
		// 验证成功后删除关于验证码的cookie
		cookie.removeCookie(httpServletResponse, null, "", "count");
		cookie.removeCookie(httpServletResponse, null,
				CookieConstants.Cookie_PATH, CookieConstants.COOKIE_CODE);

		
		SessionMessage sm;
		if (employee == null) {
			sm = sessionMessageService.getSessionMessage(user);
		} else {
			
	
			roleIds = permissionService.getRoleIds(employee.getId());

			company = (Company) companyService.getById(user.getCompanyId());
			
			sm = sessionMessageService.getSessionMessage(user, employee,
					company, roleIds);
		}
		UserCookieAuther.writeSessionMessage(sm, cookie, httpServletResponse);

		return SUCCESS;

	}

	/**
	 * 注销
	 */
	public String logout() throws BizException {

		SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();

		if(sessionMessage==null){
			
			return "login";
		}
			
		String email = sessionMessage.getUserEmail();
		
		user = userService.getUserByEmail(email);

		CookieManager cookie = new CookieManager(httpServletRequest);

		cookie.removeCookie(httpServletResponse, null, CookieConstants.Cookie_PATH,
				CookieConstants.COOKIE_PERM);

		//cookie.removeCookie(httpServletResponse, null, "", "count");

	//	cookie.removeCookie(httpServletResponse, null, CookieConstants.Cookie_PATH,
	//			CookieConstants.COOKIE_TOKEN);

		//cookie.removeCookie(httpServletResponse, null, CookieConstants.Cookie_PATH,
		//		CookieConstants.COOKIE_CODE);

		
		tokenName="true";
		return SUCCESS;
	}

	/**
	 * public String findLoginHistory() {
	 * 
	 * sessionMessage = UserHolder.getCurrentSessionMessage();
	 * 
	 * loginhistoryList = loginHistoryservice.getbyuserId(sessionMessage
	 * .getUserId());
	 * 
	 * return SUCCESS;
	 * 
	 * }
	 */


	public List<Dictionary> getSourceList() {
		return sourceList;
	}

	public void setSourceList(List<Dictionary> sourceList) {
		this.sourceList = sourceList;
	}

	public void setDictionaryReadOnlyService(
			DictionaryReadOnlyService dictionaryReadOnlyService) {
		this.dictionaryReadOnlyService = dictionaryReadOnlyService;
	}
}
